package com.sf.fy.uav.common.utils;

import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * 解密顺丰小程序参数工具类
 *
 * @author 01430312
 */
@Component
public class SfAppletParamsDecryptUtil {
    private final static Logger logger = LoggerFactory.getLogger(SfAppletParamsDecryptUtil.class);

    //测试环境的key
    @Value("${sf_applet.params.decrypt_private_key:d9d3085b8a7754f5026ae0691656c06c556076ffa79c048a09ccff1cf5f373ed}")
    private String sfAppletParamsDecryptPrivateKey;

    public String decrypt(String cipherData) {
        String privateKey = sfAppletParamsDecryptPrivateKey;
        byte[] cipherDataByte = Hex.decode(cipherData);

        //获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //构造domain参数
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(), sm2ECParameters.getN());

        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, privateKeyParameters);

        String result = null;
        try {
            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
            return new String(arrayOfBytes, "utf-8");
        } catch (Exception e) {
            logger.info("解密失败，encryptedData为{}", cipherData);
            e.printStackTrace();
        }
        return result;
    }

}
